/**
 * @file codeforces/1687/c/main
 * @brief
 * @see
 * @author Ruiming Guo (guoruiming@stu.scu.edu.cn)
 * @copyright 2022
 * @date 5/19/2022 22:24:48
 **/

#include <bits/stdc++.h>
#define rep(i, a, b) for (int i = (a); i < (int)(b); ++i)
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pi;
const int INF = 0x3f3f3f3f;
const ll LLINF = 0x3f3f3f3f3f3f3f3f;
const int N = 2e5 + 7;
int g[N][N];
int n, m;
set<pi> s;
int *find_max(int *l, int *r) {
  int val = -1, *p = nullptr;
  while (l < r) {
    if (*l >= val) {
      p = l, val = *l;
    }
    l++;
  }
  return p;
}

int *find_min(int *l, int *r) {
  int val = 0x3f3f3f3f, *p = nullptr;
  while (l < r) {
    if (*l <= val) {
      p = l, val = *l;
    }
    l++;
  }
  return p;
}
int check_sorted() {
  int ret = 0;
  rep(i, 0, n) ret += is_sorted(&g[i], &g[i] + m);
  return ret;
}
void Swap(int a, int b) { rep(i, 0, n) swap(g[i][a], g[i][b]); }
bool Sorted = bool check() {
  s.clear();
  if (check_sorted() == n) return true;
  int gm = g[0][0], gmi = 0;
  rep(j, 1, m) {
    if (g[0][j] > gm) {
      gm = g[0][j], gmi = j;
    } else if (g[0][j] < gm) {
      auto mn = find_min(g[0] + j, g[0] + m);
      int pos = mn - g[0];
      s.insert({gmi, pos});
      Swap(gmi, pos);
    }
  }
  return check_sorted() == n;
}
int main() {
  // High rating and good luck!
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int tc;
  cin >> tc;
  while (tc--) {
    cin >> m >> n;
    rep(j, 0, m) cin >> g[j];
  }
  return 0;
}
